package cc.mrbird.febs.common.datasource.starter.organization;

import com.xf.common.core.entity.FebsAuthUser;
import com.xf.common.core.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author lengleng
 * @date 2018-12-26
 * <p>
 * 租户维护处理器
 */
@Slf4j
public class OrganizationHandler implements com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler {

    @Autowired
    private OrganizationConfigProperties properties;

    /**
     * 获取租户值
     * <p>
     *
     * @return 租户值
     */
    @Override
    public Expression getTenantId(boolean where) {
        final OrganizationContextHolder.OrganizationConfig organizationConfig = OrganizationContextHolder.getOrganizationConfig();
        String organizationId = organizationConfig.getOrganizationId();
        log.debug("当前租户为 >> {}", organizationId);
        if (organizationId == null) {
            return new NullValue();
        }
        return new StringValue(organizationId);
    }

    /**
     * 获取租户字段名
     *
     * @return 租户字段名
     */
    @Override
    public String getTenantIdColumn() {
        return properties.getColumn();
    }

    /**
     * 根据表名判断是否进行过滤
     *
     * @param tableName 表名
     * @return 是否进行过滤
     */
    @Override
    public boolean doTableFilter(String tableName) {
        FebsAuthUser authUser = SecurityUtils.getUser();
        if (authUser != null && authUser.getIsGlobalAdmin()) {
            return true;
        }
        final OrganizationContextHolder.OrganizationConfig organizationConfig = OrganizationContextHolder.getOrganizationConfig();
        if (organizationConfig != null && organizationConfig.getOrganizationFlag().equals(false)) {
            return true;
        }
        return properties.getTables().contains(tableName);
    }

}
